package 康复训练_JavaGo并驾齐驱;

import 二叉树.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Jz32I从上到下打印二叉树 {

    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[]{};
        }
        List<Integer> list = new ArrayList<>();

        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.addLast(root);

        while (queue.size() > 0) {
            int count = queue.size();
            while (count > 0) {
                count--;
                TreeNode treeNode = queue.removeFirst();
                list.add(treeNode.val);
                if (treeNode.left != null) {
                    queue.addLast(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.addLast(treeNode.right);
                }
            }
        }

        int[] result = new int[list.size()];
        int index = 0;
        for (Integer i : list) {
            result[index] = i;
            index++;
        }
        return result;
    }

}
